<template>
    <div class="list-def">
        <a-form-model layout="vertical" :model="config">
            <a-form-model-item :label="$comi18('listDef.selectList','选择列表')">
                <rx-input-button v-model="config.boList" :allowInput="true" @change="changeButton" @click="selectList" @input="handInput"></rx-input-button>
                <a-checkbox class="formChenckbox" v-model="config.showName">{{i18n('list.titleDisplay','标题展示')}}</a-checkbox>
                <a-checkbox class="formChenckbox" v-model="config.fullBtn">{{customViewI18n('fullBtn','全屏按钮')}}</a-checkbox>
            </a-form-model-item>
            <a-form-model-item :label="i18n('list.dataPermission','数据权限')">
                <a-select v-model="config.pmtAlias"
                          :options="dataAuthAry"
                          :getPopupContainer="(p) => p.parentNode"
                          :allowClear="true"
                          @change="pmtAliasChange"
                >
                </a-select>
            </a-form-model-item>
        </a-form-model>
        <a-tabs default-active-key="1">
            <a-tab-pane key="1">
                <span slot="tab"> {{$comi18('listDef.receiveData','接收数据配置')}}</span>
                <a-form-model :model="config.receive" layout="vertical">
                    <a-form-model-item :label="$comi18('formDef.queryParamSource', '查询参数来源')">
                        <a-select
                            default-value="url"
                            v-model="config.receive.type"
                            :options="sourceAry"
                            :getPopupContainer="(p) => p.parentNode"
                            :allowClear="true"
                        >
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item :label="$comi18('formDef.deployeEvent', '发布事件组件')" v-if="config.receive.type == 'event'">
                        <a-select
                            v-model="config.receive.publishComponent"
                            :options="publishComponent"
                            allowClear
                            @change="changeComponent"
                            :getPopupContainer="(p) => p.parentNode"
                        >
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item style="margin-top: 50px" :label="$comi18('listDef.primary', '参数映射')">
                        <a-button-group class="abuttonhert">
                            <a-button class="abutton" @click="addParams">
                                <i class="iconjia iconfont"></i>
                            </a-button>
                            <a-button class="abutton" @click="removeSelect()">
                                <i class="icontrash iconfont"></i>
                            </a-button>

                            <a-button class="abutton" @click="moveUp()">
                                <i class="iconshang iconfont"></i>
                            </a-button>
                            <a-button class="abutton" @click="moveDown()">
                                <i class="iconxia iconfont"></i>
                            </a-button>
                        </a-button-group>
                        <a-table
                            :dataSource="config.receive.mapping"
                            :pagination="false"
                            :rowSelection="receiveRowSelection"
                            rowKey="idx_"
                            style="height: 300px"
                            :bordered="true"
                        >
                            <a-table-column :title="$comi18('rxDialog.paramName', '参数名称')" dataIndex="name">
                                <template slot-scope="text, record">
                                    <a-select
                                        v-model="record.name"
                                        :options="listParamsDef"
                                        @change="nameChange($event,record)"
                                        :getPopupContainer="(p) => p.parentNode"
                                        :allowClear="true"
                                    >
                                    </a-select>
                                </template>
                            </a-table-column>
                            <a-table-column :title="$comi18('formDef.valueSource', '值来源')" dataIndex="valueSource">
                                <template slot-scope="text, record">
                                    <a-select
                                        v-model="record.valueSource"
                                        :options="valueSourceDef"
                                        :getPopupContainer="(p) => p.parentNode"
                                        :allowClear="true"
                                    >
                                    </a-select>
                                </template>
                            </a-table-column>
                            <a-table-column :title="$comi18('rxDialog.dbObj.paramVal', '参数值')" dataIndex="valueDef">
                                <template slot-scope="text, record">
                                    <a-select
                                        v-model="record.valueDef"
                                        :options="compomentParamsDef"
                                        :allowClear="true"
                                        :getPopupContainer="(p) => p.parentNode"
                                        v-if="config.receive.type == 'event' && record.valueSource == 'param'"
                                    >
                                    </a-select>
                                    <a-select
                                        v-model="record.valueDef"
                                        :options="params"
                                        :allowClear="true"
                                        :getPopupContainer="(p) => p.parentNode"
                                        v-if="config.receive.type == 'url' && record.valueSource == 'param'"
                                    >
                                    </a-select>
                                    <a-input v-model="record.valueDef"
                                             v-if="record.valueSource == 'fixedVar'"></a-input>
                                    <a-input-group v-if="record.valueSource == 'script'" compact>
                                        <div style="display: flex">
                                            <a-input style="margin-right: 0px"  v-model="record.valueDef"/>
                                            <a-button @click="openScriptQuery(record)">...</a-button>
                                        </div>
                                    </a-input-group>
                                    <a-select
                                        v-if="record.valueSource == 'constantVar'"
                                        v-model="record.valueDef"
                                        :options="constantField"
                                        allowClear
                                        :getPopupContainer="(p) => p.parentNode"
                                    ></a-select>
                                    <a-input v-if="record.valueSource != 'fixedVar'" v-model="record.defVal" :placeholder="i18n('defaultVal','默认值')"></a-input>
                                </template>
                            </a-table-column>
                        </a-table>
                    </a-form-model-item>
                </a-form-model>
            </a-tab-pane>
            <a-tab-pane key="2">
                <span slot="tab"> {{$comi18('listDef.publishData', '发布数据配置')}} </span>
                <a-form-model-item :label="$comi18('listDef.unitParams', '组件参数')">
                    <a-button-group class="abuttonhert">
                        <a-button class="abutton" @click="reloadParams" :title="i18n('list.refresh','刷新参数')">
                            <i class="iconrefresh iconfont" ></i>
                        </a-button>
                    </a-button-group>
                    <a-table :dataSource="config.publish.paramMapping" :pagination="false" rowKey="idx_"
                             :bordered="true">
                        <a-table-column :title="$comi18('listDef.val', '值')" dataIndex="key">
                            <template slot-scope="text, record">
                                <span v-text="text"></span>
                            </template>
                        </a-table-column>
                        <a-table-column :title="$comi18('listDef.field', '字段')" dataIndex="label">
                            <template slot-scope="text, record">
                                <span v-text="text"></span>
                            </template>
                        </a-table-column>
                    </a-table>
                </a-form-model-item>
            </a-tab-pane>
        </a-tabs>
    </div>
</template>
<script>
import {RxInputButton, Util, Dialog, GridMixin, RxFit} from "@lowcode/jpaas-common-lib"
import ComponentDef from './ComponentDef'
import FormBoListApi from "@/api/form/core/formBoList";
import FormBoPermissionApi from "@/api/form/core/formBoPermission";

export default {
    name: 'list-def',
    mixins: [GridMixin, ComponentDef],

    components: {
        RxInputButton,
        RxFit,
    },
    created() {
        this.init()
    },
    computed: {
        receiveRowSelection() {
            return {
                selectedRowKeys: this.selectedRowKeys,
                onChange: this.onSelectChange,
            }
        },
    },
    data() {
        return {
            boListObj: {},
            selectedRowKeys: [],
            publishSelectRowKeys: [],
            config: {
                boList: "{value:'',text:''}",
                pmtAlias:'',
                component: 'list-component',
                alias: '',
                name: '',
                showName: true,
                fullBtn: false,
                receive: {
                    //url,event
                    type: '',
                    publishComponent: '',
                    mapping: [],
                },
                publish: {
                    paramMapping: [],
                },
                listParamsDef: [],
            },
            sourceAry: [
                {value: 'url', label: this.i18n('form.incomParam','来自传入参数')},
                {value: 'event', label: this.$comi18('formDef.fromComponent', '来自组件')},
            ],
            dataAuthAry:[],
            publishComponent: [],
            listParamsDef: [],
            compomentParamsDef: [],
            valueSourceDef: [
                {value: 'param', label: this.$ti18('rxForm.param', '参数传入')},
                {value: 'fixedVar', label: this.$ti18('rxForm.fixedVar','固定值')},
                {value: 'script', label: this.$ti18('rxForm.script','脚本')},
                {value: 'constantVar', label: this.$ti18('rxForm.constantVar','常量')},
            ],
            fields: [],
        }
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formComponent", key);
        },
        openScriptQuery(record) {
            Dialog.openScripttextDialog(
                {
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                    zIndex: 99999,
                    data: {script: record.valueDef},
                },
                function (self, data) {
                    record.valueDef = data
                }
            )
        },
        cancel() {
            Util.closeWindow(this, 'cancel')
        },
        selectList(vm) {
            var conf = {
                curVm: this,
                data: {
                    single: true,
                    isDialog: 'NO',
                },
                widthHeight: ['1000px', '600px'],
                zIndex: 999999,
            }
            var self_ = this;
            Dialog.openFormBoListDialog(conf, function (self, data) {
                if (!data || data.length == 0) {
                    self_.$notification.warning({
                        message: self_.$ti18('rxMsa.tipsInfo','提示信息'),
                        description: self_.$comi18('listDef.selectFormBoList', '请选择一个列表!'),
                    })
                    return
                }
                var obj = data[0]

                var isExist = self_.isAliasExist(obj.key)
                if (isExist) {
                    return
                }
                self_.boListObj = obj;
                if (obj.searchJson) {
                    var paramsJson = JSON.parse(obj.searchJson).filter((item) => item.type === 'income')
                    self_.handListParamsDef(paramsJson)
                }
                self_.handFields(obj.fieldsJson)
                self_.handPublishConf(obj.publishConf)
                self_.handDataAuths(obj.key)
                self_.config.boList = `{value:'${obj.key}',text:'${obj.name}'}`
                self_.config.alias = obj.key
                self_.config.name = obj.name;
                if (self_.type != 'drag') {
                    self_.$emit('formSubmit', self_.config, self_.index, self_.type, self_.item)
                } else {
                    self_.$emit('dragclick', self_.config, self_.index, self_.type)
                }
            })
        },
        reloadParams() {
            FormBoListApi.getByKey(this.config.alias).then(res => {
                var obj = res.data;
                this.handPublishConf(obj.publishConf)
            })
        },
        getType(type) {
            var typeObj = {string: 'S', number: 'I', date: 'D'}
            if (typeObj[type]) {
                return typeObj[type]
            }
            return 'S'
        },
        handListParamsDef(searchJson) {

            this.listParamsDef = [];
            this.config.listParamsDef = []
            for (var i = 0; i < searchJson.length; i++) {
                var obj = searchJson[i];
                let autoFilter=obj.autoFilter;
                //日期范围
                if(obj.fc=="rangepicker"){
                    var val =  obj.fieldName;
                    var values =['Q_' + tabPre + obj.fieldName + '_D_GE','Q_' + tabPre + obj.fieldName + '_D_LE'];
                    if(autoFilter=='NO'){
                        values =[obj.fieldName +"_START" ,obj.fieldName + +"_END"];
                    }
                    var o = {value: val, label: obj.fieldLabel,type: obj.fc,values:values};
                    this.listParamsDef.push(o);
                    this.config.listParamsDef.push(o);
                }else {
                    var tabPre = obj.tablePre ? obj.tablePre + '.' : ''
                    var type = this.getType(obj.dataType);
                    var val = 'Q_' + tabPre + obj.fieldName + '_' + type + '_' + obj.fieldOp;
                    if(autoFilter=='NO'){
                        val=obj.fieldName;
                    }
                    var o = {value: val, label: obj.fieldLabel,type: obj.fc}
                    this.listParamsDef.push(o);
                    this.config.listParamsDef.push(o);
                }
            }
        },
        pmtAliasChange(value,option){
            var isExist=this.isPmtAliasExist(this.config.alias,value);
            if(isExist){
                this.config.pmtAlias=option.context.value;
                return;
            }
            if (this.type != 'drag') {
                this.$emit('formSubmit', this.config, this.index, this.type, this.item)
            } else {
                this.$emit('dragclick', this.config, this.index, this.type)
            }
        },
        handDataAuths(key){
            var self=this;
            FormBoPermissionApi.getListByKey(key).then(res=>{
                let ary=res.data.list || [];
                self.dataAuthAry=ary.map(item=>{
                    return {label:item.name,value:item.permissionId};
                })
            })
        },
        handFields(fieldsJson) {
            fieldsJson = JSON.parse(fieldsJson)
            for (var i = 0; i < fieldsJson.length; i++) {
                var obj = fieldsJson[i]
                var o = {value: obj.field, label: obj.header}
                this.fields.push(o)
            }
        },
        handPublishConf(conf) {
            if (!conf) {
                return
            }
            conf = JSON.parse(conf)
            this.config.publish.paramMapping = conf;
        },
        addParams() {
            if (this.config.receive.type == 'url') {
                if (!this.params || this.params.length==0) {
                    this.$notification.warning({
                        message: this.$ti18('rxMsa.tipsInfo','提示信息'),
                        description: this.i18n('msg.configure','未配置传入参数，请去配置!'),
                    })
                    return;
                }
            }
            // if (this.config.receive.mapping.length >= this.listParamsDef.length) {
            //     this.$notification.warning({
            //         message: '提示信息',
            //         description: '该数据列表未配置传入参数，请去配置!',
            //     })
            //     return;
            // }
            this.config.receive.mapping.push({idx_: Util.randomId(), name: '', valueSource: '', valueDef: '',type:"",defVal:""})
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys
        },
        moveUp() {
            this.toUp(this.config.receive.mapping, this.selectedRowKeys)
        },
        moveDown() {
            this.toDown(this.config.receive.mapping, this.selectedRowKeys)
        },
        removeSelect() {
            this.removeRows(this.config.receive.mapping, this.selectedRowKeys)
        },

        onPublishSelectChange(selectedRowKeys) {
            this.publishSelectRowKeys = selectedRowKeys
        },
        movePublishUp() {
            this.toUp(this.config.publish.paramMapping, this.publishSelectRowKeys)
        },
        movePublishDown() {
            this.toDown(this.config.publish.paramMapping, this.publishSelectRowKeys)
        },
        removePublishSelect() {
            this.removeRows(this.config.publish.paramMapping, this.publishSelectRowKeys)
        },

        addPublishParams() {
            this.config.publish.paramMapping.push({idx_: Util.randomId(), name: '', valueSource: 'param', valueDef: ''})
        },
        handOk() {
            if (!this.config.alias) {
                this.$notification.warning({message: this.$ti18('rxMsa.tipsInfo','提示信息'), description: this.i18n('msg.selectList','请先选择一个列表!')})
                return
            }

            var mapping = this.config.publish.paramMapping
            for (var i = 0; i < mapping.length; i++) {
                var param = mapping[i]
                this.setFieldName(param)
            }
            Util.closeWindow(this, 'ok', this.config)
        },
        setFieldName(param) {
            var field = param.field
            for (var i = 0; i < this.fields.length; i++) {
                var o = this.fields[i]
                if (o.value == field) {
                    param.name = o.label
                }
            }
        },
        handInput(data) {
            if (!data) {
                this.config.alias = ''
                this.config.name = ''
            }
        },
        changeButton(val){
            this.config.name = eval("(" + val + ")").text
        },
        init() {
            if (this.conf.listParamsDef) {
                this.config = this.conf
                this.listParamsDef = this.config.listParamsDef
                this.changeComponent(this.config.receive.publishComponent)
                this.handDataAuths(this.config.alias)
            }
            this.publishComponent = this.getPublishOptions()
        },
        changeComponent(val) {
            if (!val) {
                return;
            }
            if (this.config.alias == val) {
                this.config.receive.publishComponent = ''
                this.$notification.warning({message: this.$ti18('rxMsa.tipsInfo','提示信息'), description:  this.$comi18('formDef.cannotSelectEvent', '发布事件组件不能选择自己!')})
                return
            }
            this.compomentParamsDef = this.getPubParams(val)
        },
        nameChange(value,record){
            var param= this.listParamsDef.find(item=>item.value==value);
            record.type=param.type;
            if(param.type=='rangepicker'){
                this.$set(record,"values",param.values);
            }
        },
    }
}
</script>

<style scoped>
.abutton {
    width: 28px;
    height: 28px;
    background-color: #f5f7fa;
}

.abutton i {
    margin-left: -8px;
}

.abuttonhert {
    float: right;
    margin-top: -30px;
    border-radius: 4px;
    margin-bottom: 10px;
}

.formChenckbox {
    margin-top: 9px;
}

.list-def {
    padding: 0 10px;
}
</style>